﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using Company.Core.Config;
using Company.Sqlite.Interfaces;
using MaterialDesignThemes.Wpf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using 无人值守地磅称重系统.Dialogs;
using 无人值守地磅称重系统.Interfaces;
using 无人值守地磅称重系统.Models.Login;
using 无人值守地磅称重系统.Models.Message;

namespace 无人值守地磅称重系统.ViewModels
{

    internal class LoginViewModel : ObservableObject
    {
        public ICommand LoginCommand { get;  }

        public ICommand LoadCommand { get; }

        public ISession Session { get;  }

        public IUserRepository UserRepository { get; }

        public IConfigManager ConfigManager { get; }

        public LoginViewModel(ISession session, IUserRepository userRepository, IConfigManager configManager)
        {
            Session= session;
            UserRepository= userRepository;
            ConfigManager= configManager;
            LoginCommand = new RelayCommand(Login);
            LoadCommand = new RelayCommand(Load);
        }

        private void Load()
        {
            var user = ConfigManager.Read<LoginUser>(ConfigKey.LoginUser) ?? new LoginUser();
            Session.CurrentUser.UserName = user.UserName;
        }

        private void Login()
        {
            Session.CurrentUser.Password = "12345678";
            if(string.IsNullOrEmpty(Session.CurrentUser.UserName) || string.IsNullOrEmpty(Session.CurrentUser.Password))
            {
                //MessageBox.Show("用户名或密码为空");
                //DialogHost.Show(new Dialog("用户名或密码为空"), "RootDialog");
                Session.Show("用户名或密码为空");
                return;
            }
            var list = UserRepository.GetAll();
            var user = list.Find(t => t.UserName== Session.CurrentUser.UserName && t.Password == Session.CurrentUser.Password);
            if (user != null)
            {
                // todo 进入首页
                WeakReferenceMessenger.Default.Send(new LoginSuccessMessage(user));
            }
            else
            {
                //MessageBox.Show("用户名或密码错误");
                //DialogHost.Show(new Dialog(), "RootDialog");
                Session.Show("用户名或密码错误");
            }
        }
    }
}
